#!/usr/bin/env pwsh

<#
.SYNOPSIS
    使用外部 RabbitMQ 服务器启动 WebRTC 项目

.DESCRIPTION
    此脚本帮助您配置并启动连接到外部 RabbitMQ 服务器的 WebRTC 应用。
    您需要提供 RabbitMQ 服务器的连接信息。

.PARAMETER RabbitMQHost
    RabbitMQ 服务器地址

.PARAMETER RabbitMQPort
    RabbitMQ 端口（默认 5672）

.PARAMETER RabbitMQUser
    RabbitMQ 用户名

.PARAMETER RabbitMQPassword
    RabbitMQ 密码

.PARAMETER VirtualHost
    RabbitMQ 虚拟主机（默认 /）

.PARAMETER UseTLS
    是否使用 TLS 连接（默认 false）

.EXAMPLE
    .\start-with-external-rabbitmq.ps1 -RabbitMQHost "mq.example.com" -RabbitMQUser "myuser" -RabbitMQPassword "mypass"
#>

param(
    [Parameter(Mandatory = $true)]
    [string]$RabbitMQHost,
    
    [Parameter(Mandatory = $false)]
    [int]$RabbitMQPort = 5672,
    
    [Parameter(Mandatory = $true)]
    [string]$RabbitMQUser,
    
    [Parameter(Mandatory = $true)]
    [string]$RabbitMQPassword,
    
    [Parameter(Mandatory = $false)]
    [string]$VirtualHost = "/",
    
    [Parameter(Mandatory = $false)]
    [bool]$UseTLS = $false,
    
    [Parameter(Mandatory = $false)]
    [string]$IncomingQueue = "webrtc.incoming",
    
    [Parameter(Mandatory = $false)]
    [string]$OutgoingQueue = "webrtc.outgoing",
    
    [Parameter(Mandatory = $false)]
    [string]$NotificationQueue = "webrtc.notifications"
)

Write-Host "=== WebRTC 项目 - 外部 RabbitMQ 连接启动脚本 ===" -ForegroundColor Green

# 检查必要文件
$requiredFiles = @(
    "appsettings.json",
    "WebRtcProject.csproj"
)

foreach ($file in $requiredFiles) {
    if (-not (Test-Path $file)) {
        Write-Error "找不到必要文件: $file"
        Write-Host "请确保在项目根目录运行此脚本" -ForegroundColor Red
        exit 1
    }
}

# 设置环境变量
Write-Host "配置 RabbitMQ 连接参数..." -ForegroundColor Yellow

$env:RabbitMQ__HostName = $RabbitMQHost
$env:RabbitMQ__Port = $RabbitMQPort
$env:RabbitMQ__UserName = $RabbitMQUser
$env:RabbitMQ__Password = $RabbitMQPassword
$env:RabbitMQ__VirtualHost = $VirtualHost
$env:RabbitMQ__UseTLS = $UseTLS.ToString().ToLower()
$env:RabbitMQ__Enabled = "true"

# 设置队列配置
$env:RabbitMQ__TargetQueues__IncomingQueue = $IncomingQueue
$env:RabbitMQ__TargetQueues__OutgoingQueue = $OutgoingQueue
$env:RabbitMQ__TargetQueues__NotificationQueue = $NotificationQueue

Write-Host "RabbitMQ 配置:" -ForegroundColor Cyan
Write-Host "  服务器: $RabbitMQHost:$RabbitMQPort" -ForegroundColor White
Write-Host "  用户名: $RabbitMQUser" -ForegroundColor White
Write-Host "  虚拟主机: $VirtualHost" -ForegroundColor White
Write-Host "  使用 TLS: $UseTLS" -ForegroundColor White
Write-Host "  队列配置:" -ForegroundColor White
Write-Host "    - 传入队列: $IncomingQueue" -ForegroundColor White
Write-Host "    - 传出队列: $OutgoingQueue" -ForegroundColor White
Write-Host "    - 通知队列: $NotificationQueue" -ForegroundColor White

# 测试 RabbitMQ 连接
Write-Host "`n测试 RabbitMQ 连接..." -ForegroundColor Yellow

try {
    $tcpClient = New-Object System.Net.Sockets.TcpClient
    $tcpClient.Connect($RabbitMQHost, $RabbitMQPort)
    $tcpClient.Close()
    Write-Host "✓ RabbitMQ 服务器连接测试成功" -ForegroundColor Green
} catch {
    Write-Warning "⚠ 无法连接到 RabbitMQ 服务器 ${RabbitMQHost}:${RabbitMQPort}"
    Write-Host "请检查:" -ForegroundColor Yellow
    Write-Host "  1. 服务器地址和端口是否正确" -ForegroundColor White
    Write-Host "  2. 网络连接是否正常" -ForegroundColor White
    Write-Host "  3. 防火墙设置" -ForegroundColor White
    
    $continue = Read-Host "是否继续启动应用？(y/N)"
    if ($continue -ne "y" -and $continue -ne "Y") {
        Write-Host "启动已取消" -ForegroundColor Red
        exit 1
    }
}

# 检查并生成 SSL 证书
Write-Host "`n检查 SSL 证书..." -ForegroundColor Yellow

if (-not (Test-Path "certs\cert.pfx")) {
    Write-Host "SSL 证书不存在，正在生成..." -ForegroundColor Yellow
    
    if (Test-Path "scripts\generate-certs-final.ps1") {
        & "scripts\generate-certs-final.ps1"
    } else {
        Write-Warning "找不到证书生成脚本，将使用默认配置"
    }
} else {
    Write-Host "✓ SSL 证书已存在" -ForegroundColor Green
}

# 启动应用
Write-Host "`n启动 WebRTC 应用..." -ForegroundColor Green

try {
    # 设置开发环境
    $env:ASPNETCORE_ENVIRONMENT = "Development"
    $env:ASPNETCORE_URLS = "http://localhost:5000;https://localhost:5001"
    
    Write-Host "正在启动应用..." -ForegroundColor Yellow
    Write-Host "应用地址:" -ForegroundColor Cyan
    Write-Host "  HTTP:  http://localhost:5000" -ForegroundColor White
    Write-Host "  HTTPS: https://localhost:5001" -ForegroundColor White
    Write-Host "  API文档: https://localhost:5001/swagger" -ForegroundColor White
    Write-Host "  RabbitMQ状态: https://localhost:5001/api/rabbitmq/status" -ForegroundColor White
    
    Write-Host "`n按 Ctrl+C 停止应用" -ForegroundColor Yellow
    Write-Host "====================================`n" -ForegroundColor Green
    
    # 启动应用
    dotnet run --project .
    
} catch {
    Write-Error "启动应用失败: $_"
    
    # 检查端口占用
    Write-Host "`n检查端口占用..." -ForegroundColor Yellow
    $ports = @(5000, 5001)
    
    foreach ($port in $ports) {
        $connection = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue
        if ($connection) {
            Write-Host "端口 $port 被进程 $($connection.OwningProcess) 占用" -ForegroundColor Red
            $process = Get-Process -Id $connection.OwningProcess -ErrorAction SilentlyContinue
            if ($process) {
                Write-Host "  进程名: $($process.ProcessName)" -ForegroundColor Red
            }
        }
    }
    
    Write-Host "`n请运行以下脚本清理端口占用:" -ForegroundColor Yellow
    Write-Host "  .\scripts\kill-dotnet-processes.ps1" -ForegroundColor White
    
    exit 1
}

Write-Host "`n应用已退出" -ForegroundColor Yellow 